package com.example.camerastudy.slice;

import com.example.camerastudy.ResourceTable;
import ohos.aafwk.ability.AbilitySlice;
import ohos.aafwk.content.Intent;
import ohos.media.audio.AudioManager;
import ohos.media.audio.SoundPlayer;
import ohos.media.audio.ToneDescriptor;

/**
 * @author : frank
 * @date : 2021/3/1 11:00
 */
public class SoundSlice extends AbilitySlice {

    private SoundPlayer soundPlayer;

    private int soundId = -1;

    @Override
    protected void onStart(Intent intent) {
        super.onStart(intent);
        super.setUIContent(ResourceTable.Layout_slice_sound);
        findComponentById(ResourceTable.Id_button_play_resources).setClickedListener(component -> {
            playResources();
        });

        findComponentById(ResourceTable.Id_button_pause_play_resources).setClickedListener(component -> {
            pausePlayResource();
        });

        findComponentById(ResourceTable.Id_button_play_tone).setClickedListener(component -> {
            playTone();
        });

        findComponentById(ResourceTable.Id_button_play_system).setClickedListener(component -> {
            playSystemMusic();
        });
    }

    private void playSystemMusic() {
        // 步骤1：实例化对象
        SoundPlayer soundPlayer = new SoundPlayer("packageName");
        // 步骤2：播放键盘敲击音，音量为1.0
        soundPlayer.playSound(SoundPlayer.SoundType.KEY_CLICK, 1.0f);
    }

    private void playTone() {
        // 步骤1：实例化对象
        SoundPlayer soundPlayer = new SoundPlayer();
        // 步骤2：创建DTMF_0（高频1336Hz，低频941Hz）持续时间1000ms的tone音
        soundPlayer.createSound(ToneDescriptor.ToneType.DTMF_0, 1000);
        // 步骤3：tone音播放，暂停和资源释放
        soundPlayer.play();
        soundPlayer.pause();
        soundPlayer.release();
    }

    private void playResources() {
        // 步骤1：实例化对象

        // 步骤2：指定音频资源加载并创建短音
        soundPlayer = new SoundPlayer(AudioManager.AudioVolumeType.STREAM_MUSIC.getValue());
        soundId = soundPlayer.createSound(getContext(), ResourceTable.Media_testmp3);
        soundPlayer.setOnCreateCompleteListener((soundPlayer1, i, i1) -> {
            // soundPlayer.play(soundId);
            // 步骤3：指定音量，循环次数和播放速度
            SoundPlayer.SoundPlayerParameters parameters = new SoundPlayer.SoundPlayerParameters();
            parameters.setVolumes(new SoundPlayer.AudioVolumes());
            parameters.setSpeed(1.5f);
            parameters.setLoop(2);
            soundPlayer.setLoop(soundId,2);
            // 步骤4：短音播放
            soundPlayer.play(soundId, parameters);
        });
    }

    private void pausePlayResource() {
        soundPlayer.stop(soundId);
        //soundPlayer.stop(soundId);
        //soundPlayer.release();
    }
}
